package com.cl.ks.service;


import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONObject;
import com.cl.ks.entity.ClueAutoResult;
import com.cl.ks.repository.ClueAutoResultRepository;
import com.cl.ks.utils.DbUtil;
import com.cl.mvc.service.BaseService;
import org.apache.parquet.Strings;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Service
public class ClueAutoResultService extends BaseService<ClueAutoResult> {

    private final DbUtil dbUtil;

    protected ClueAutoResultService(ClueAutoResultRepository ClueAutoResultRepository, DbUtil dbUtil) {
        super(ClueAutoResultRepository);
        this.dbUtil = dbUtil;
    }
    public ResponseEntity<String> getClueSourceData(Integer filterId, HttpServletResponse response) {
        List<ClueAutoResult> clueAutoResultList = findByField("filterId", String.valueOf(filterId));
        Map<String, List<Map<String, Object>>> clueSourceData = getClueSourceData(clueAutoResultList);
        return downloadData(clueSourceData,response);
    }
    public Map<String, List<Map<String, Object>>> getClueSourceData(Integer filterId) {
        List<ClueAutoResult> clueAutoResultList = findByField("filterId", String.valueOf(filterId));
        return getClueSourceData(clueAutoResultList);
    }

    public Map<String, List<Map<String, Object>>> getClueSourceData(List<ClueAutoResult> clueAutoResultList) {
        Map<String, List<Map<String, Object>>> res = new HashMap<>();
        Map<String, List<String>> dbCodeAndSourceData = new HashMap<>();
        Map<String,ClueAutoResult> idAndClueAutoResult = new HashMap<>();

        for (ClueAutoResult clueAutoResult : clueAutoResultList) {
            String dbCode = clueAutoResult.getDbCode();
            String tableName = clueAutoResult.getTableName();
            String key = dbCode + "-" + tableName;
            dbCodeAndSourceData.putIfAbsent(key, new ArrayList<>());
            List<String> idList = dbCodeAndSourceData.get(key);
            idList.add(clueAutoResult.getSourceId());
            idAndClueAutoResult.put(clueAutoResult.getSourceId(),clueAutoResult);
        }

        dbCodeAndSourceData.forEach((key, value) -> {
            String[] split = key.split("-");
            List<String> idList = dbCodeAndSourceData.get(key);
            String ids = "(" + Strings.join(idList, ",") + ")";
            String dbCode = split[0];
            String tableName = split[1];
            List<Map<String, Object>> maps = dbUtil.fetchSQL(dbCode, "select * from " + tableName + " where id in " + ids);
            maps.forEach(map->{
                ClueAutoResult clueAutoResult = idAndClueAutoResult.get(String.valueOf(map.get("id")));
                map.put("ruleId",clueAutoResult.getRuleId());
                map.put("ruleName",clueAutoResult.getRuleName());
            });
            res.put(key,maps);
        });
        return res;
    }

    public ResponseEntity<String> downloadData( Map<String, List<Map<String, Object>>> data, HttpServletResponse response) {
        try {
            ExcelWriter writer = null; // 创建一个新的 Excel 工作簿

            // 遍历 map 中的每一项
            for (Map.Entry<String, List<Map<String, Object>>> entry : data.entrySet()) {
                String sheetName = entry.getKey();
                List<Map<String, Object>> dataList = entry.getValue();

                if (writer == null) {
                    writer = ExcelUtil.getWriterWithSheet(sheetName);
                } else {
                    writer.setSheet(sheetName); // 第一个参数是工作表的名称，第二个参数指定是否覆盖原有数据
                }
                // 为每一个键创建一个新的工作表
                writer.write(dataList, true); // 写入数据
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=result.xlsx"); // 注意这里使用 .xlsx 扩展名

            // 获取输出流
            ServletOutputStream out = response.getOutputStream();

            // 输出 Excel 文件
            Objects.requireNonNull(writer).flush(out, true);
            writer.close();
            IoUtil.close(out);
            return ResponseEntity.status(HttpStatus.OK).body("下载成功");
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("下载失败");
        }
    }


}
